package com.zhentao.service;

import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * MinIO服务类
 * 提供文件上传、下载、删除等功能
 * 
 * @author zhentao
 */
@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.url-prefix}")
    private String urlPrefix;

    /**
     * 检查存储桶是否存在
     */
    public boolean bucketExists(String bucketName) throws MinioException {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new MinioException("检查存储桶失败: " + e.getMessage());
        }
    }

    /**
     * 创建存储桶
     */
    public void createBucket() throws MinioException {
        try {
            boolean found = bucketExists(bucketName);
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                System.out.println("存储桶 '" + bucketName + "' 创建成功");
            } else {
                System.out.println("存储桶 '" + bucketName + "' 已存在");
            }
        } catch (Exception e) {
            throw new MinioException("创建存储桶失败: " + e.getMessage());
        }
    }

    /**
     * 文件上传
     * @param file 文件
     * @param folder 文件夹路径，例如 "medicine", "avatar", "article"
     * @return 文件完整URL
     */
    public String uploadFile(MultipartFile file, String folder) throws MinioException {
        if (file.isEmpty()) {
            throw new MinioException("上传文件不能为空");
        }
        
        try {
            // 确保存储桶存在
            createBucket();

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = (folder != null && !folder.isEmpty() ? folder + "/" : "") +
                                UUID.randomUUID().toString() + fileExtension;

            InputStream inputStream = file.getInputStream();
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            inputStream.close();
            
            String fileUrl = urlPrefix + objectName;
            System.out.println("文件上传成功: " + fileUrl);
            return fileUrl;
        } catch (Exception e) {
            throw new MinioException("MinIO文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    public boolean deleteFile(String objectName) throws MinioException {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            System.out.println("文件删除成功: " + objectName);
            return true;
        } catch (Exception e) {
            throw new MinioException("MinIO文件删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件信息
     */
    public StatObjectResponse getFileInfo(String objectName) throws MinioException {
        try {
            return minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            throw new MinioException("获取文件信息失败: " + e.getMessage());
        }
    }
}

